<?php

namespace IDock\Insurance\ZFIC\Request;

use Exception;
use IDock\Insurance\ZFIC\Response\CommonResponse;
use IDock\Insurance\ZFIC\ZFICEnums;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

class OrderPriceQueryRequest extends AllZFICRequest
{

    protected $urlTip = '询价申请接口';

    protected $route = 'order/api/order/kindplan';

    protected $response = CommonResponse::class;

    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    /**
     * @throws Exception
     */
    public function generate(): array
    {
        $vehicleInfo = $this->visitor->getVehicleVisitor();
        $owner = $this->visitor->getOwnerVisitor();
        $insured = $this->visitor->getInsuredVisitor();
        $applicant = $this->visitor->getApplicantVisitor();
        $carUsageCode = $this->getCIVehicleCode($vehicleInfo->useNatureCode,$vehicleInfo->carKindCode,$vehicleInfo->attachNature,$vehicleInfo->causeType);//车辆使用性质
        $param = [
            'businessNo' => $this->visitor->getExtInfoVisitor()->argc['businessNo'] ?? '',
            'licenseNo' => $vehicleInfo->licenseNo ?: '暂未上牌',
            'frameNo' => $vehicleInfo->vin,
            'engineNo' => $vehicleInfo->engineNo,
            'singeinDate' => $vehicleInfo->firstRegisterDate,
            'carOwner' => $owner->name,
            'carOwnerType' => $owner->typeCode == 'R1' ? '1' : '2' ,//1:个人 2:团体,
            'carOwnerIdentifyType' => ZFICEnums::$certificateTypeCode[$owner->certificateTypeCode],
            'identifyNumber' => $owner->certificateNo,
            'carOwnerPhone' => $owner->mobile,
            'chgOwnerFlag' => ($vehicleInfo->isTransfer or $vehicleInfo->isCiTransfer)  ? '01' : '0',
            'transferDate' => $vehicleInfo->transferDate,
            'modelCode' => $vehicleInfo->vehicleModelCode,
            'platOrderNo' => $this->visitor->getExtInfoVisitor()->argc['platOrderNo'] ?? '',
            'certificateType' => '',
            'certificateNO' => '',
            'certificateDate' => '',
            'insuredName' => $insured->name,
            'carKindCode' => ZFICEnums::$carKindCode[$vehicleInfo->carKindCode],//车辆(机动车)种类
            'carUseType' => $carUsageCode,//使用性质
            'attachNature' => ZFICEnums::$attachNature[$vehicleInfo->attachNature],
            'licenseTypeCode' => ZFICEnums::$licenseTypeCode[$vehicleInfo->licenseTypeCode],//号牌种类
            'vehicleCategory' => $vehicleInfo->vehicleStyleCode,//交管车辆类型
            'licenseColor' => $vehicleInfo->licenseColorCode,
            'fuelTypeCode' => ZFICEnums::$energyType1[$vehicleInfo->energyTypeCode],
            'seatCount' => $vehicleInfo->vehicleSeat,
            'completeKerbMass' => round((int)$vehicleInfo->wholeWeight / 1000,2),
            'tonCount' => (string)(intval($vehicleInfo->vehicleTonnage ?? 0) / 1000),
            'jqStartDate' => $this->visitor->ciStartData,
            'jqEndDate' => $this->visitor->ciEndData,
            'syStartDate' => $this->visitor->biStartData,
            'syEndDate' => $this->visitor->biEndData,
            'groupCode' => '',
            'insuredType' => $applicant->typeCode == 'R1' ? '1' : '2' ,//1:个人 2:团体, 投保人类型
            'appliInsuredName' => $applicant->name,
            'carOwnerGender' => '',//车主性别
            'carOwnerBirthDate' => '',//车主生日
            'appliIdentifyType' => ZFICEnums::$certificateTypeCode[$applicant->certificateTypeCode],//投保人证件类型
            'appliIdentifyNumber' => $applicant->certificateNo,
            'riskInsuredType' => $insured->typeCode == 'R1' ? '1' : '2',
            'insuredIdentifyType' => ZFICEnums::$certificateTypeCode[$insured->certificateTypeCode],
            'insuredIdentifyNumber' => $insured->certificateNo,
            'modelEnergyType' => $this->visitor->getVehicleVisitor()->isNewEnergy ? ZFICEnums::$modelEnergyType[$vehicleInfo->energyTypeCode] : '' ,//燃料（能源）种类 新能源车必传
            'pureRange' => $vehicleInfo->pureRange,
            'otherEnergyTypeDesc' => '',//燃料（能源）种类为9-其他时必传
        ];

        //单商业 单交强 起保日期默认
        if (!$this->visitor->biStartData and $this->visitor->ciStartData) {
            $param['syStartDate'] = $this->visitor->ciStartData;
            $param['syEndDate'] = $this->visitor->ciEndData;
        }

        if ($this->visitor->biStartData and !$this->visitor->ciStartData) {
            $param['jqStartDate'] = $this->visitor->biStartData;
            $param['jqEndDate'] = $this->visitor->biEndData;
        }

        if(isset($vehicleInfo->argc['modelType'])){
            $param['modelCode'] = '';
            $param['ciModelCode'] = $vehicleInfo->vehicleModelCode;
            $param['pk'] = $vehicleInfo->argc['pk'] ?? '';
            $param['exhaustScale'] = $vehicleInfo->vehicleExhaust;
            $param['power'] = $vehicleInfo->power;
            $param['carName'] = $vehicleInfo->argc['carName'] ?? '';
            $param['familyName'] = $vehicleInfo->argc['carName'] ?? '';
            $param['brandName'] = $vehicleInfo->argc['brandName'] ?? '';
            $param['printBrandName'] = $vehicleInfo->argc['printBrandName'] ?? '';
            $param['carBrand'] = $vehicleInfo->argc['carBrand'] ??'';
            $param['purchasePrice'] = $vehicleInfo->vehiclePriceWithOutTax;
            $param['noticeType'] = $vehicleInfo->argc['noticeType'] ?? '';
            $param['tonCount'] = round($vehicleInfo->vehicleTonnage,3);
//            $param['completeKerbMass'] = round($vehicleInfo->wholeWeight,3);
        }
        //交强险终保日期
        if($this->visitor->ciEffectFlag){
            $param['jqEndDate'] = date('Y-m-d 23:59:59',strtotime($this->visitor->ciEndData));
        }
        if($this->visitor->biEffectFlag){
            $param['syEndDate'] = date('Y-m-d 23:59:59',strtotime($this->visitor->biEndData));
        }
        if(empty($param['carOwnerPhone'])){
            throw new Exception("车主手机号不能为空");
        }
        if(strlen($param['carOwnerPhone']) > 11){
            throw new Exception("车主手机号不能超过11位");
        }
        //投保人为个人
        if($param['carOwnerType'] == '1'){
            $param['carOwnerGender'] = $this->getGenderByIDCard($param['identifyNumber']);
            $param['carOwnerBirthDate'] = $this->getBirthday($param['identifyNumber']);
        }
        if(empty($param['carOwnerIdentifyType'])){
            throw new Exception("不支持该车主的证件类型");
        }
        if(empty($param['appliIdentifyType'])){
            throw new Exception("不支持该投保人的证件类型");
        }
        if(empty($param['insuredIdentifyType'])){
            throw new Exception("不支持该被保人的证件类型");
        }
        if(empty($param['carKindCode'])){
            throw new Exception("不支持该车辆(机动车)种类");
        }
        if(empty($param['licenseTypeCode'])){
            throw new Exception("不支持该号牌种类");
        }
        if(empty($param['fuelTypeCode'])){
            throw new Exception("不支持该能源类型");
        }

        //新车备案
        if ($this->visitor->vehicleVisitor->carCertificateType) {
            $param['certificateType'] = $this->visitor->vehicleVisitor->carCertificateType;
            $param['certificateNO'] = $this->visitor->vehicleVisitor->carCertificateNo;
            $param['certificateDate'] = $this->visitor->vehicleVisitor->carCertificateDate ? date('Y-m-d',strtotime($this->visitor->vehicleVisitor->carCertificateDate)) : '';
        }

        return $param;
    }

    /**
     * @param $useNatureCode
     * @param $carKindCode
     * @param $attachNature
     * @param $causeType
     * @return string
     * @throws Exception
     */
    public function getCIVehicleCode($useNatureCode,$carKindCode,$attachNature,$causeType): string
    {
        $useNatureCode = ZFICEnums::$useNatureCode[$useNatureCode];
        $carKindCode = ZFICEnums::$carKindCode[$carKindCode];
        $attachNature = ZFICEnums::$attachNature[$attachNature];
        $causeType = substr($causeType,1,2);
        $vehicleUsage = $useNatureCode.$carKindCode.$attachNature.$causeType;
        if(!in_array($vehicleUsage,[
            '021000101',
            '021000303',
            '022009999',
            '022309999',
            '022109999',
            '021000202',
            '011009904',
            '011009905',
            '011009907',
            '011000306',
            '012009908',
            '012309908',
            '013209908',
            '012109908',
            '019999909',
            '029999909',
        ])){
            throw new Exception("不支持的车辆使用性质");
        }
        return $vehicleUsage;
    }

    /**
     * 通过身份证获取性别
     * @param $idCard
     * @return string
     * @throws Exception
     */
    public function getGenderByIDCard($idCard): string
    {
        if(strlen($idCard) != 18){
            throw new Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard,16,1)) % 2;
        return $gender ? '1' : '2';
    }

    /**
     * @throws Exception
     */
    public function getBirthday($idCard): string
    {
        if(strlen($idCard) != 18){
            throw new Exception("身份证位数不合法");
        }
        return substr($idCard,6,4).'-'.substr($idCard,10,2).'-'.substr($idCard,12,2);
    }

    public function getStaffConfig(&$chalCode, &$userCode)
    {
        $chalCode = $this->visitor->getExtInfoVisitor()->argc['chalCode'] ?? '';
        $userCode = $this->visitor->getExtInfoVisitor()->argc['userCode'] ?? '';
    }

}
